package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;




import cn.itcast.bos.dao.take_delivery.OrderDao;
import cn.itcast.bos.dao.take_delivery.WorkBillDao;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.service.base.FixedAreaService;
import cn.itcast.bos.service.take_delivery.OrderService;
import cn.itcast.bos.utils.Constants;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	private AreaService areaService;
	
	@Autowired
	private OrderDao orderDao;
	
	@Autowired
	private FixedAreaService fixedAreaService;
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	
	@Autowired
	private WorkBillDao workDao;

	@Override
	public void saveOrder(final Order order) {
		//设置order的一些属性
		order.setOrderNum(UUID.randomUUID().toString());
		order.setOrderTime(new Date());
		order.setStatus("1");
		//得到页面输入的area
		Area sendArea = order.getSendArea();
		Area recArea = order.getRecArea();
		//根据用户输入的area从数据库里拿到持久态的area，防止直接保存用户输入的瞬时态的area，保存报错
		Area perSendArea = areaService.findByProvinceAndCityAndDistrict(sendArea.getProvince(),sendArea.getCity(),sendArea.getDistrict());
		Area perRecArea = areaService.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(), recArea.getDistrict());
		order.setSendArea(perSendArea);
		order.setRecArea(perRecArea);
		//跟据详细地址来得到定区ID
		String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/findFixedAreaIdByAddress?address="+order.getSendAddress()).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).get(String.class);
		//如果能拿到定区id
		if (fixedAreaId!=null){
			FixedArea fixedArea = fixedAreaService.findFixedAreaByfixedAreaId(fixedAreaId);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()) {
				Courier courier = iterator.next();
				//保存订单
				saveOrder(order, courier);
				//产生 工单，发送短信
				generateWorkBill(order);
				System.out.println("第一种自动分单");
				return;
			}
		}
		
		//根据详细地址找不到定区，根据详细地址匹配分区的关键自来找到定区
		if(fixedAreaId==null){
			//得到区域中的分区
			Set<SubArea> subareas = perSendArea.getSubareas();
			//遍历分区
			for (SubArea subArea : subareas) {
				//根据用户的详细地址匹配分区
				if (order.getSendAddress().contains(subArea.getKeyWords())) {
					//根据分区来找到定区
					FixedArea fixedArea = subArea.getFixedArea();
					//根据定区找到快递员
					Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
					if (iterator.hasNext()) {
						Courier courier = iterator.next();
						//保存订单
						saveOrder(order, courier);
						//生成工单，发送短信
						generateWorkBill(order);
						System.out.println("第二种自动分单");
						return;
					}
					break;
				}
			}
			
			//遍历分区,用辅助关键字来查找
			for (SubArea subArea : subareas) {
				//根据用户的详细地址匹配分区
				if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
					//根据分区来找到定区
					FixedArea fixedArea = subArea.getFixedArea();
					//根据定区找到快递员
					Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
					if (iterator.hasNext()) {
						Courier courier = iterator.next();
						//保存订单
						saveOrder(order, courier);
						//生成工单，发送短信
						generateWorkBill(order);
						System.out.println("第二种自动分单");
						return;
					}
					break;
				}
			}
		}
		//设置状态，保存订单，让客服人员处理
		order.setOrderType("2");
		orderDao.save(order);
	}
	
	//保存订单
	private void saveOrder(final Order order, Courier courier) {
		//设置状态为自动分单
		order.setOrderType("1");
		//快递员关联订单
		order.setCourier(courier);
		//保存快递员
		orderDao.save(order);
	}
	
	//生成工单
	private void generateWorkBill(final Order order) {
		final WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getSendMobileMsg());
		workBill.setSmsNumber(RandomStringUtils.randomNumeric(4));
		workDao.save(workBill);
		//发送短信
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage message = session.createMapMessage();
				message.setString("telephone", order.getCourier().getTelephone());
				message.setString("content", "你好：有一件货物需要你上门去取,客户姓名:"+order.getSendName()+",客户地址:"+order.getSendAddress()+",客户电话:"+order.getTelephone()+",用户给快递员捎话:"+order.getSendMobileMsg()+"。短信编号:"+workBill.getSmsNumber());
				return message;
			}
		});
		//更改状态
		workBill.setPickstate("已通知");
	}

	@Override
	public Order findOrderByOrderNum(String orderNum) {
		
		return orderDao.findByOrderNum(orderNum);
	}
}
